package com.example.rushbuy.service;

import com.example.rushbuy.event.BuyEvent;
import com.example.rushbuy.mapper.OrderMapper;
import com.example.rushbuy.mapper.RushItemMapper;
import com.example.rushbuy.po.Order;
import com.example.rushbuy.po.RushItem;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RushItemMapper rushItemMapper;

    public boolean order(Integer itemId,Integer userId,Integer count){
        Integer price = 100;
        //检查redis库存
        //直接库存-1，保证原子性
//        Object obj = redisTemplate.opsForValue().get("store");
        Object obj = redisTemplate.opsForValue().decrement("store:"+itemId,count);
        Integer storeCount = Integer.parseInt(obj.toString());
        if(storeCount >= 0){
            System.out.println("用户id:"+userId+"抢到了!");
//            //创建订单
//            Order order = new Order();
//            order.setItemId(itemId);
//            order.setUserId(userId);
//            order.setTotalPrice(price * count);
//            order.setBuyCount(count);
//            order.setPayState(0);
//            order.setIsTimeout(false);
//            orderMapper.insert(order);
//            //减少库存
//            RushItem rushItem = rushItemMapper.selectByPrimaryKey(order.getItemId());
//            rushItem.setStore(rushItem.getStore() - order.getBuyCount());
//            //此处高并发下会有问题，需要加一个分布式锁
//            rushItemMapper.updateByPrimaryKey(rushItem);

            //符合条件的全部推送mq
            //推送mq
            BuyEvent event = new BuyEvent();
            event.setItemId(itemId);
            event.setUserId(userId);
            event.setCount(count);
            event.setPrice(price);
            event.setTotalPrice(price * count);
            rocketMQTemplate.convertAndSend("rushbuy",event);
            return true;
        }else{
            System.out.println("用户id:"+userId+"没有抢到!");
            redisTemplate.opsForValue().set("store:"+itemId,0);
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean payProcess(Integer itemId,Integer userId){
        Order order = orderMapper.findOneByItemIdAndUserIdAndIsTimeoutAndPayState(itemId, userId,false,0);
        if(order != null){
            //说明已经成功下单，
            order.setPayState(1);
            orderMapper.updateByPrimaryKey(order);
            return true;
        }else
            return false;

    }

}
